{
  "name": "Case 78 - Sales Manager - Decision Maker Activity Monitor",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 9 * * 1"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -1040,
        -192
      ],
      "id": "2d6556d7-4aac-4559-9caa-a1067da5b36b",
      "name": "Weekly Schedule - Monday 9 AM"
    },
    {
      "parameters": {
        "actorId": {
          "__rl": true,
          "value": "buIWk2uOUzTmcLsuB",
          "mode": "list",
          "cachedResultName": "Linkedin Post Search Scraper (No Cookies) (harvestapi/linkedin-post-search)",
          "cachedResultUrl": "https://console.apify.com/actors/buIWk2uOUzTmcLsuB/input"
        },
        "customBody": "{\n  \"authorUrls\": [\n    \"https://www.linkedin.com/company/target-company-1\",\n    \"https://www.linkedin.com/company/target-company-2\",\n    \"https://www.linkedin.com/company/target-company-3\",\n    \"https://www.linkedin.com/in/ceo-prospect-1\",\n    \"https://www.linkedin.com/in/vp-sales-prospect-2\",\n    \"https://www.linkedin.com/in/cto-prospect-3\",\n    \"https://www.linkedin.com/in/cfo-prospect-4\",\n    \"https://www.linkedin.com/company/enterprise-prospect-1\",\n    \"https://www.linkedin.com/company/enterprise-prospect-2\"\n  ],\n  \"searchKeywords\": [\n    \"challenge\",\n    \"problem\",\n    \"looking for\",\n    \"need help\",\n    \"frustrated\",\n    \"solution\"\n  ],\n  \"maxPosts\": 50,\n  \"postedLimit\": \"week\",\n  \"scrapeComments\": false,\n  \"scrapeReactions\": false\n}"
      },
      "type": "@apify/n8n-nodes-apify.apify",
      "typeVersion": 1,
      "position": [
        -848,
        -192
      ],
      "id": "4c6a6a79-ecf6-436b-a64d-64ae475811c6",
      "name": "Scrape LinkedIn Decision Maker Posts",
      "credentials": {
        "apifyApi": {
          "id": "w5S6YBbbyUddEfQA",
          "name": "Apify account"
        }
      }
    },
    {
      "parameters": {
        "resource": "Datasets",
        "datasetId": "={{ $json.defaultDatasetId }}"
      },
      "type": "@apify/n8n-nodes-apify.apify",
      "typeVersion": 1,
      "position": [
        -656,
        -192
      ],
      "id": "b26a7c67-9f2f-440b-89c7-acecdf7b8260",
      "name": "Get Dataset Items",
      "credentials": {
        "apifyApi": {
          "id": "w5S6YBbbyUddEfQA",
          "name": "Apify account"
        }
      }
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-4o-mini",
          "mode": "list",
          "cachedResultName": "GPT-4o-mini"
        },
        "responses": {
          "values": [
            {
              "role": "system",
              "content": "=You are a Sales Opportunity Validation Expert.\n\nAnalyze LinkedIn posts to determine if they indicate genuine business pain points or buying signals.\n\nReturn ONLY valid JSON in this exact format:\n{\n  \"is_sales_opportunity\": \"yes|no\",\n  \"confidence\": 0.95,\n  \"reason\": \"brief explanation\"\n}\n\nCriteria for \"yes\" (genuine sales opportunity):\n✅ Expresses specific business problem or challenge\n✅ Mentions frustration with current solution/process\n✅ Actively seeking recommendations or solutions\n✅ Budget or investment discussions related to solving problem\n✅ Timeline urgency indicators (\"need ASAP\", \"by end of quarter\")\n✅ Comparison shopping or vendor evaluation\n✅ Decision-maker expressing pain point (VP, Director, C-level)\n✅ \"Looking for\" + specific solution category\n\nCriteria for \"no\" (NOT a sales opportunity):\n❌ Vague complaints without specific problem\n❌ Personal/non-business frustrations\n❌ Already purchased a solution (satisfied customer posts)\n❌ Rhetorical questions or thought leadership content\n❌ Seeking free advice for DIY solution\n❌ Junior employees without buying authority\n❌ General industry discussion without personal pain\n❌ Celebrations or success stories\n\nRules:\n1. confidence: 0-1 scale (0.9+ for very clear buying signals)\n2. reason: 1 sentence explaining the decision\n3. Be strict - require actual pain point + potential budget authority\n4. Return ONLY the JSON object, no explanations"
            },
            {
              "content": "=Analyze this LinkedIn post to determine if it's a sales opportunity:\n\nAuthor: {{ $json.author.name }}\nAuthor Info: {{ $json.author.info }}\nPost Date: {{ $json.postedAt.date }}\nPost Content: {{ $json.content }}\n\nReturn only JSON."
            }
          ]
        },
        "builtInTools": {},
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.1,
      "position": [
        -496,
        -192
      ],
      "id": "c22fa262-7d14-48cf-b92e-c204bcf52798",
      "name": "AI Validation Filter",
      "credentials": {
        "openAiApi": {
          "id": "ICwxUBbatsF2sDvy",
          "name": "OpenAi account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// UNIVERSAL AI RESPONSE PARSER - Same code for ALL cases\nconst items = [];\nconst input = $input.all();\n\nfunction extractJSON(text) {\n  const jsonMatch = text.match(/\\{[\\s\\S]*\\}/);\n  if (!jsonMatch) return null;\n  return jsonMatch[0];\n}\n\ninput.forEach((item, index) => {\n  try {\n    let aiText = item.json.output[0].content[0].text || '';\n    \n    // Clean markdown code blocks\n    aiText = aiText\n      .replace(/```json/gi, '')\n      .replace(/```/g, '')\n      .trim();\n    \n    // Extract JSON object\n    const jsonStr = extractJSON(aiText);\n    \n    if (!jsonStr) {\n      throw new Error('No JSON found in AI response');\n    }\n    \n    // Parse and return clean JSON\n    const parsed = JSON.parse(jsonStr);\n    items.push({ json: parsed });\n    \n  } catch (error) {\n    console.error(`Parse error for item ${index}:`, error.message);\n    // Return empty object on error - no case-specific fields\n    items.push({ json: {} });\n  }\n});\n\nreturn items;"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -208,
        -192
      ],
      "id": "41343c58-5c7e-4918-b545-158164c4fc89",
      "name": "Parse AI Validation"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "is_sales_opportunity",
              "name": "is_sales_opportunity",
              "value": "={{ $json.is_sales_opportunity }}",
              "type": "string"
            },
            {
              "id": "confidence",
              "name": "confidence",
              "value": "={{ $json.confidence }}",
              "type": "number"
            },
            {
              "id": "reason",
              "name": "reason",
              "value": "={{ $json.reason }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -32,
        -192
      ],
      "id": "bdcd6ca6-89c4-47b1-b74b-22f40272cd59",
      "name": "Edit Fields - Validation"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 1
          },
          "conditions": [
            {
              "id": "condition-001",
              "leftValue": "={{ $json.is_sales_opportunity }}",
              "rightValue": "yes",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2,
      "position": [
        144,
        -192
      ],
      "id": "a49caf6a-9220-45e2-abad-5de8af333032",
      "name": "Filter Only Sales Opportunities"
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-4o-mini",
          "mode": "list",
          "cachedResultName": "GPT-4o-mini"
        },
        "responses": {
          "values": [
            {
              "role": "system",
              "content": "=You are a Sales Intelligence Analyst.\n\nExtract structured sales opportunity information from LinkedIn posts.\n\nReturn ONLY valid JSON in this exact format:\n{\n  \"decision_maker_name\": \"Person's name who posted\",\n  \"company_name\": \"Their company name\",\n  \"job_title\": \"Their role/title if available\",\n  \"pain_point_category\": \"Cost|Time|Efficiency|Integration|Scalability|Compliance|Quality|Other\",\n  \"pain_point_description\": \"Brief description of their problem (max 150 chars)\",\n  \"urgency_signals\": \"Immediate|This Quarter|This Year|No Timeline|Unclear\",\n  \"budget_indicators\": \"Budget Mentioned|Cost Concerns|No Budget Info\",\n  \"current_solution_mentioned\": \"Yes - [solution name]|No\",\n  \"buying_stage\": \"Awareness|Consideration|Decision|Post-Purchase\",\n  \"outreach_recommendation\": \"Comment on Post|Send DM|Send Email|Wait and Monitor\"\n}\n\nExtraction Rules:\n1. decision_maker_name: Extract from author info\n2. company_name: Extract from author profile\n3. job_title: Extract from author info if available\n4. pain_point_category: Categorize the main problem\n5. pain_point_description: Summarize their specific challenge\n6. urgency_signals: Look for timeline indicators in post\n7. budget_indicators: Check for cost/budget mentions\n8. current_solution_mentioned: What are they using now?\n9. buying_stage: Assess where they are (Awareness = just realized problem, Consideration = comparing options, Decision = ready to buy)\n10. outreach_recommendation: Based on post tone and urgency, recommend best approach\n\nReturn ONLY the JSON object, no explanations."
            },
            {
              "content": "=Extract sales intelligence from this LinkedIn post:\n\nAuthor: {{ $('Get Dataset Items').item.json.author.name }}\nAuthor Info: {{ $('Get Dataset Items').item.json.author.info }}\nPost Date: {{ $('Get Dataset Items').item.json.postedAt.date }}\nPost Content: {{ $('Get Dataset Items').item.json.content }}\nEngagement: {{ $('Get Dataset Items').item.json.engagement.likes }} likes, {{ $('Get Dataset Items').item.json.engagement.comments }} comments\n\nReturn only JSON."
            }
          ]
        },
        "builtInTools": {},
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.1,
      "position": [
        304,
        -192
      ],
      "id": "9765fe69-2d29-4b6a-af03-b64bdc212538",
      "name": "AI Extract Sales Intelligence",
      "credentials": {
        "openAiApi": {
          "id": "ICwxUBbatsF2sDvy",
          "name": "OpenAi account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// UNIVERSAL AI RESPONSE PARSER - Same code for ALL cases\nconst items = [];\nconst input = $input.all();\n\nfunction extractJSON(text) {\n  const jsonMatch = text.match(/\\{[\\s\\S]*\\}/);\n  if (!jsonMatch) return null;\n  return jsonMatch[0];\n}\n\ninput.forEach((item, index) => {\n  try {\n    let aiText = item.json.output[0].content[0].text || '';\n    \n    // Clean markdown code blocks\n    aiText = aiText\n      .replace(/```json/gi, '')\n      .replace(/```/g, '')\n      .trim();\n    \n    // Extract JSON object\n    const jsonStr = extractJSON(aiText);\n    \n    if (!jsonStr) {\n      throw new Error('No JSON found in AI response');\n    }\n    \n    // Parse and return clean JSON\n    const parsed = JSON.parse(jsonStr);\n    items.push({ json: parsed });\n    \n  } catch (error) {\n    console.error(`Parse error for item ${index}:`, error.message);\n    // Return empty object on error - no case-specific fields\n    items.push({ json: {} });\n  }\n});\n\nreturn items;"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        576,
        -192
      ],
      "id": "eb057a7d-b573-479c-b282-1f65dfebdd38",
      "name": "Parse AI Response"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "timestamp",
              "name": "analysis_timestamp",
              "value": "={{ new Date().toISOString() }}",
              "type": "string"
            },
            {
              "id": "decision_maker",
              "name": "decision_maker_name",
              "value": "={{ $json.decision_maker_name }}",
              "type": "string"
            },
            {
              "id": "company",
              "name": "company_name",
              "value": "={{ $json.company_name }}",
              "type": "string"
            },
            {
              "id": "job_title",
              "name": "job_title",
              "value": "={{ $json.job_title }}",
              "type": "string"
            },
            {
              "id": "pain_category",
              "name": "pain_point_category",
              "value": "={{ $json.pain_point_category }}",
              "type": "string"
            },
            {
              "id": "pain_description",
              "name": "pain_point_description",
              "value": "={{ $json.pain_point_description }}",
              "type": "string"
            },
            {
              "id": "urgency",
              "name": "urgency_signals",
              "value": "={{ $json.urgency_signals }}",
              "type": "string"
            },
            {
              "id": "budget",
              "name": "budget_indicators",
              "value": "={{ $json.budget_indicators }}",
              "type": "string"
            },
            {
              "id": "current_solution",
              "name": "current_solution_mentioned",
              "value": "={{ $json.current_solution_mentioned }}",
              "type": "string"
            },
            {
              "id": "buying_stage",
              "name": "buying_stage",
              "value": "={{ $json.buying_stage }}",
              "type": "string"
            },
            {
              "id": "outreach",
              "name": "outreach_recommendation",
              "value": "={{ $json.outreach_recommendation }}",
              "type": "string"
            },
            {
              "id": "author_profile",
              "name": "author_profile",
              "value": "={{ $('Get Dataset Items').item.json.author?.linkedinUrl || '' }}",
              "type": "string"
            },
            {
              "id": "author_info",
              "name": "author_info",
              "value": "={{ $('Get Dataset Items').item.json.author?.info || '' }}",
              "type": "string"
            },
            {
              "id": "post_content",
              "name": "post_content",
              "value": "={{ $('Get Dataset Items').item.json.content || '' }}",
              "type": "string"
            },
            {
              "id": "post_date",
              "name": "post_date",
              "value": "={{ $('Get Dataset Items').item.json.postedAt?.date || '' }}",
              "type": "string"
            },
            {
              "id": "post_url",
              "name": "post_url",
              "value": "={{ $('Get Dataset Items').item.json.linkedinUrl || '' }}",
              "type": "string"
            },
            {
              "id": "likes",
              "name": "likes_count",
              "value": "={{ $('Get Dataset Items').item.json.engagement?.likes || 0 }}",
              "type": "number"
            },
            {
              "id": "comments",
              "name": "comments_count",
              "value": "={{ $('Get Dataset Items').item.json.engagement?.comments || 0 }}",
              "type": "number"
            },
            {
              "id": "shares",
              "name": "shares_count",
              "value": "={{ $('Get Dataset Items').item.json.engagement?.shares || 0 }}",
              "type": "number"
            },
            {
              "id": "total_engagement",
              "name": "engagement_total",
              "value": "={{ ($('Get Dataset Items').item.json.engagement?.likes || 0) + ($('Get Dataset Items').item.json.engagement?.comments || 0) + ($('Get Dataset Items').item.json.engagement?.shares || 0) }}",
              "type": "number"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        736,
        -192
      ],
      "id": "dba07cca-fa4f-4c73-a4c0-5554489707c1",
      "name": "Edit Fields"
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "1niZ35MCIhisQa1Pa7cHleXRoNUxgv8n79a8Bj6eFDtw",
          "mode": "list",
          "cachedResultName": "Case 78 - Sales opportunity Log",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1niZ35MCIhisQa1Pa7cHleXRoNUxgv8n79a8Bj6eFDtw/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Sheet1",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1niZ35MCIhisQa1Pa7cHleXRoNUxgv8n79a8Bj6eFDtw/edit#gid=0"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Analysis_Date": "={{ $json.analysis_timestamp }}",
            "Decision_Maker_Name": "={{ $json.decision_maker_name }}",
            "Company_Name": "={{ $json.company_name }}",
            "Job_Title": "={{ $json.job_title }}",
            "Pain_Point_Category": "={{ $json.pain_point_category }}",
            "Pain_Point_Description": "={{ $json.pain_point_description }}",
            "Urgency_Signals": "={{ $json.urgency_signals }}",
            "Budget_Indicators": "={{ $json.budget_indicators }}",
            "Current_Solution": "={{ $json.current_solution_mentioned }}",
            "Buying_Stage": "={{ $json.buying_stage }}",
            "Outreach_Recommendation": "={{ $json.outreach_recommendation }}",
            "Author_Profile": "={{ $json.author_profile }}",
            "Post_Date": "={{ $json.post_date }}",
            "Likes": "={{ $json.likes_count }}",
            "Comments": "={{ $json.comments_count }}",
            "Shares": "={{ $json.shares_count }}",
            "Total_Engagement": "={{ $json.engagement_total }}",
            "Post_URL": "={{ $json.post_url }}",
            "Post_Content": "={{ $json.post_content }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "Analysis_Date",
              "displayName": "Analysis_Date",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Decision_Maker_Name",
              "displayName": "Decision_Maker_Name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Company_Name",
              "displayName": "Company_Name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Job_Title",
              "displayName": "Job_Title",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Pain_Point_Category",
              "displayName": "Pain_Point_Category",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Pain_Point_Description",
              "displayName": "Pain_Point_Description",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Urgency_Signals",
              "displayName": "Urgency_Signals",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Budget_Indicators",
              "displayName": "Budget_Indicators",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Current_Solution",
              "displayName": "Current_Solution",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Buying_Stage",
              "displayName": "Buying_Stage",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Outreach_Recommendation",
              "displayName": "Outreach_Recommendation",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Author_Profile",
              "displayName": "Author_Profile",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Post_Date",
              "displayName": "Post_Date",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Likes",
              "displayName": "Likes",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Comments",
              "displayName": "Comments",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Shares",
              "displayName": "Shares",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Total_Engagement",
              "displayName": "Total_Engagement",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Post_URL",
              "displayName": "Post_URL",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Post_Content",
              "displayName": "Post_Content",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        880,
        -192
      ],
      "id": "c4d4bea7-c2c0-412d-976a-ea834e5b1580",
      "name": "Log to Google Sheet",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "LOs2dbk9lby0NfDM",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Aggregate all items from Google Sheets into email-ready summary\nconst allItems = $input.all();\n\n// Count by pain point category\nconst painPointCounts = {};\nallItems.forEach(item => {\n  const category = item.json.Pain_Point_Category || 'Other';\n  painPointCounts[category] = (painPointCounts[category] || 0) + 1;\n});\n\n// Count by buying stage\nconst buyingStageCounts = {};\nallItems.forEach(item => {\n  const stage = item.json.Buying_Stage || 'Unclear';\n  buyingStageCounts[stage] = (buyingStageCounts[stage] || 0) + 1;\n});\n\n// Count by urgency\nconst urgencyCounts = {};\nallItems.forEach(item => {\n  const urgency = item.json.Urgency_Signals || 'No Timeline';\n  urgencyCounts[urgency] = (urgencyCounts[urgency] || 0) + 1;\n});\n\n// Count opportunities with budget mentioned\nconst budgetMentioned = allItems.filter(item => \n  item.json.Budget_Indicators === 'Budget Mentioned'\n).length;\n\n// Immediate follow-up opportunities\nconst immediateOpportunities = allItems.filter(item => \n  item.json.Urgency_Signals === 'Immediate' || \n  item.json.Buying_Stage === 'Decision'\n);\n\n// Group by outreach recommendation\nconst outreachCounts = {};\nallItems.forEach(item => {\n  const outreach = item.json.Outreach_Recommendation || 'Wait and Monitor';\n  outreachCounts[outreach] = (outreachCounts[outreach] || 0) + 1;\n});\n\n// Top companies (most opportunities)\nconst companyCounts = {};\nallItems.forEach(item => {\n  const company = item.json.Company_Name || 'Unknown';\n  companyCounts[company] = (companyCounts[company] || 0) + 1;\n});\n\nconst topCompanies = Object.entries(companyCounts)\n  .sort((a, b) => b[1] - a[1])\n  .slice(0, 10);\n\n// Build HTML table rows\nconst tableRows = allItems.map(item => {\n  const data = item.json;\n  const urgencyColor = data.Urgency_Signals === 'Immediate' ? '#dc3545' : \n                       data.Urgency_Signals === 'This Quarter' ? '#ffc107' : '#6c757d';\n  \n  return `\n    <tr>\n      <td>${data.Decision_Maker_Name || 'N/A'}</td>\n      <td>${data.Company_Name || 'N/A'}</td>\n      <td>${data.Pain_Point_Category || 'N/A'}</td>\n      <td>${data.Buying_Stage || 'N/A'}</td>\n      <td><span style=\"color: ${urgencyColor}; font-weight: bold;\">${data.Urgency_Signals || 'N/A'}</span></td>\n      <td>${data.Outreach_Recommendation || 'N/A'}</td>\n      <td><a href=\"${data.Post_URL || '#'}\">View</a></td>\n    </tr>\n  `;\n}).join('');\n\n// Return single aggregated item\nreturn {\n  json: {\n    week_start: new Date(Date.now() - 7*24*60*60*1000).toISOString().split('T')[0],\n    week_end: new Date().toISOString().split('T')[0],\n    total_opportunities: allItems.length,\n    pain_point_breakdown: Object.entries(painPointCounts),\n    buying_stage_breakdown: Object.entries(buyingStageCounts),\n    urgency_breakdown: Object.entries(urgencyCounts),\n    budget_mentioned_count: budgetMentioned,\n    immediate_opportunities_count: immediateOpportunities.length,\n    outreach_breakdown: Object.entries(outreachCounts),\n    top_companies: topCompanies,\n    table_rows: tableRows,\n    all_opportunities: allItems.map(item => item.json)\n  }\n};"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1056,
        -192
      ],
      "id": "397e6270-cebc-4c9f-b86b-54b65eb62f11",
      "name": "Aggregate Weekly Summary"
    },
    {
      "parameters": {
        "sendTo": "sales-team@yourcompany.com",
        "subject": "=📊 Weekly Sales Opportunity Report: {{ $json.week_start }} to {{ $json.week_end }}",
        "message": "=WEEKLY SALES OPPORTUNITY INTELLIGENCE REPORT\n================================================\nReport Period: {{ $json.week_start }} to {{ $json.week_end }}\n\nOVERVIEW:\nTotal Opportunities Identified: {{ $json.total_opportunities }}\nImmediate Follow-up Required: {{ $json.immediate_opportunities_count }}\nBudget Mentioned: {{ $json.budget_mentioned_count }}\n\nPAIN POINT BREAKDOWN:\n{{ $json.pain_point_breakdown.map(([category, count]) => category + ': ' + count).join('\\n') }}\n\nBUYING STAGE DISTRIBUTION:\n{{ $json.buying_stage_breakdown.map(([stage, count]) => stage + ': ' + count).join('\\n') }}\n\nURGENCY ANALYSIS:\n{{ $json.urgency_breakdown.map(([urgency, count]) => urgency + ': ' + count).join('\\n') }}\n\nOUTREACH RECOMMENDATIONS:\n{{ $json.outreach_breakdown.map(([action, count]) => action + ': ' + count).join('\\n') }}\n\nTOP COMPANIES (Most Opportunities):\n{{ $json.top_companies.map(([company, count], i) => (i+1) + '. ' + company + ' (' + count + ' opportunities)').join('\\n') }}\n\n🔥 PRIORITY ACTION:\n{{ $json.immediate_opportunities_count }} opportunities require immediate follow-up!\n\nFull opportunity details in Google Sheets.\n\nGenerated: {{ new Date().toLocaleDateString() }}",
        "options": {}
      },
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1232,
        -192
      ],
      "id": "8b8b672b-868f-4982-b523-8204013b95f8",
      "name": "Send Weekly Summary Email",
      "webhookId": "f8d5086d-ac55-427b-b01d-c4becee50952",
      "credentials": {
        "gmailOAuth2": {
          "id": "cyqCGWcggZNMcSOv",
          "name": "Gmail account"
        }
      }
    }
  ],
  "pinData": {},
  "connections": {
    "Weekly Schedule - Monday 9 AM": {
      "main": [
        [
          {
            "node": "Scrape LinkedIn Decision Maker Posts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Scrape LinkedIn Decision Maker Posts": {
      "main": [
        [
          {
            "node": "Get Dataset Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Dataset Items": {
      "main": [
        [
          {
            "node": "AI Validation Filter",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Validation Filter": {
      "main": [
        [
          {
            "node": "Parse AI Validation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse AI Validation": {
      "main": [
        [
          {
            "node": "Edit Fields - Validation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Edit Fields - Validation": {
      "main": [
        [
          {
            "node": "Filter Only Sales Opportunities",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter Only Sales Opportunities": {
      "main": [
        [
          {
            "node": "AI Extract Sales Intelligence",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Extract Sales Intelligence": {
      "main": [
        [
          {
            "node": "Parse AI Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse AI Response": {
      "main": [
        [
          {
            "node": "Edit Fields",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Edit Fields": {
      "main": [
        [
          {
            "node": "Log to Google Sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log to Google Sheet": {
      "main": [
        [
          {
            "node": "Aggregate Weekly Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Aggregate Weekly Summary": {
      "main": [
        [
          {
            "node": "Send Weekly Summary Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "eb97aa14-cf2e-4a53-b2a2-27df7b4863f9",
  "meta": {
    "instanceId": "3a43da28588548e21903e71cf1dc3ddd65c24bf0c62e7e4b77542ffe87ad79c6"
  },
  "id": "FQzemmwCdbPSJN6r",
  "tags": []
}